package org.OpenGeoPortal.Download;

import java.util.*;
import java.io.*; 

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

import org.xml.sax.*;
import org.json.simple.parser.*;
import org.w3c.dom.*;

public class MetadataFromSolr implements MetadataRetriever {
	private LayerInfoRetriever layerInfoRetriever;
	//private String xmlString;
	
	public void setLayerInfoRetriever(LayerInfoRetriever layerInfoRetriever){
		this.layerInfoRetriever = layerInfoRetriever;
	}
	
	/*public void setXMLString(String xmlString) throws ParserConfigurationException, IOException, SAXException, TransformerException{
		this.xmlString = xmlString;
		this.filterXMLString(xmlString);
	}*/
	
	String filterXMLString(String rawXMLString)
	 throws ParserConfigurationException, IOException, SAXException, TransformerException
	 {
		//parse the returned XML to make sure it is well-formed & to format
		//filter extra spaces from xmlString
		rawXMLString = rawXMLString.replaceAll(">[ \t\n\r\f]+<", "><").replaceAll("[\t\n\r\f]+", "");


		// Create a factory
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// Use document builder factory
		DocumentBuilder builder = factory.newDocumentBuilder();
		//Parse the document
		InputStream xmlInputStream = new ByteArrayInputStream(rawXMLString.getBytes("UTF-8"));
		Document document = builder.parse(xmlInputStream);

		Source xmlSource = new DOMSource(document);
		StringWriter stringWriter = new StringWriter();
		StreamResult streamResult = new StreamResult(stringWriter);
		
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

		transformer.transform(xmlSource, streamResult);
		String outputString = stringWriter.toString();

		return outputString;
	 }
	
	/*public String getXMLStream() throws UnsupportedEncodingException{

		int fileSize = this.xmlString.getBytes("UTF-8").length;
		
		return xmlString;
	}*/
	
	private String getXMLStringFromSolr(String layerName) throws IOException, ParseException{
		Map<String,String> conditionsMap = new HashMap<String, String>();
		int i = layerName.indexOf(":");
		if (i > 0){
			//String workSpace = layerName.substring(0, i);
			//conditionsMap.put("WorkspaceName", workSpace);
			layerName = layerName.substring(i + 1);
		}
		conditionsMap.put("Name", layerName);
		List<String> fieldSet = new ArrayList<String>();
		fieldSet.add("FgdcText");
		Map<String, Map<String,String>>layerInfo = this.layerInfoRetriever.getInfo(conditionsMap, fieldSet, true);
		String XMLString = layerInfo.get(layerInfo.keySet().iterator().next()).get("FgdcText");

		return XMLString;
	}
	
	String filterFileName(String layerName){
		//remove the workspace name prefix if it exists
		layerName = layerName.substring(layerName.indexOf(":") + 1);
		//replace periods with underscores
		layerName = layerName.replace(".", "_");
		return layerName;
	}
	
	public File getXMLFile(String metadataLayerName, File xmlFile) throws IOException, ParseException, ParserConfigurationException, SAXException, TransformerException{
		String xmlString = this.getXMLStringFromSolr(metadataLayerName);
		xmlString = this.filterXMLString(xmlString);
		//write this string to a file
		OutputStream xmlFileOutputStream = new FileOutputStream (xmlFile);
		new PrintStream(xmlFileOutputStream).print(xmlString);
		return xmlFile;
	}

}
